const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

const formatTime = (date) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};

// 复制到本地临时路径，方便预览
const getLocalUrl = (path, name) => {
  const fs = wx.getFileSystemManager();
  const tempFileName = `${wx.env.USER_DATA_PATH}/${name}`;
  fs.copyFileSync(path, tempFileName);
  return tempFileName;
};

// 图片URL映射表，将云存储URL转换为实际的TCB HTTP URL
const imageUrlMap = {
  // 头像类 - 聊天头像
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Sean.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/chat/avatar-Sean.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Mollymolly.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/chat/avatar-Mollymolly.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Andrew.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/chat/avatar-Andrew.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Kingdom.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/chat/avatar-Kingdom.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Paige.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/chat/avatar-Paige.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/avatar1.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/avatar1.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/bg_navbar2.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/bg_navbar2.png',
  
  // 图标资源
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_wx.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/icon_wx.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_qq.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/icon_qq.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_doc.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/icon_doc.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_map.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/icon_map.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_td.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/icon_td.png',
  'cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/img_td.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/img_td.png',
  
  // 卡片图片 - 使用实际的TCB URL
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/card0.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/card0.png',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/card1.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/card1.png',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/card2.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/card2.png',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/card3.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/card3.png',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/card4.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/card4.png',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/swiper0.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/swiper0.png',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/swiper1.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/swiper1.png',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/home/swiper2.png': 'https://636c-cloud1-6g22e569b6b129d5-1380223701.tcb.qcloud.la/static/home/swiper2.png',
  
  // 发布页图片 - 使用占位图片
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/image1.png': 'https://via.placeholder.com/300x200/4A90E2/FFFFFF?text=图片1',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/image2.png': 'https://via.placeholder.com/300x200/50E3C2/FFFFFF?text=图片2',
  
  // 个人信息页面图片
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/avatar1.png': 'https://via.placeholder.com/100x100/4A90E2/FFFFFF?text=用户',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/img_td.png': 'https://via.placeholder.com/60x60/50E3C2/FFFFFF?text=客服',
  
  // 聊天头像
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Sean.png': 'https://via.placeholder.com/80x80/4A90E2/FFFFFF?text=Sean',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Mollymolly.png': 'https://via.placeholder.com/80x80/50E3C2/FFFFFF?text=Molly',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Andrew.png': 'https://via.placeholder.com/80x80/F5A623/FFFFFF?text=Andrew',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Kingdom.png': 'https://via.placeholder.com/80x80/BD10E0/FFFFFF?text=Kingdom',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/chat/avatar-Paige.png': 'https://via.placeholder.com/80x80/7ED321/FFFFFF?text=Paige',
  
  // 服务图标
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_wx.png': 'https://via.placeholder.com/60x60/1AAD19/FFFFFF?text=微信',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_qq.png': 'https://via.placeholder.com/60x60/12B7F5/FFFFFF?text=QQ',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_doc.png': 'https://via.placeholder.com/60x60/4285F4/FFFFFF?text=文档',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_map.png': 'https://via.placeholder.com/60x60/34A853/FFFFFF?text=地图',
  '@cloud://cloud1-6g22e569b6b129d5.636c-cloud1-6g22e569b6b129d5-1380223701/static/icon_td.png': 'https://via.placeholder.com/60x60/0052D9/FFFFFF?text=TD'
};

// 转换云存储URL为可用的图片URL（同步版本，用于向后兼容）
const convertCloudUrl = (url) => {
  if (typeof url !== 'string') return url;
  
  // 如果有映射，使用映射的URL（保持向后兼容）
  if (imageUrlMap[url]) {
    return imageUrlMap[url];
  }
  
  // 如果是云存储URL但没有映射，返回空字符串
  if (url.startsWith('@cloud://') || url.startsWith('cloud://')) {
    return '';
  }
  
  // 其他情况直接返回原URL
  return url;
};

// 异步版本的convertCloudUrl，返回带签名的临时URL
const convertCloudUrlAsync = async (url) => {
  if (typeof url !== 'string') return url;
  
  // 如果是云存储URL，使用getTempFileURL获取临时URL
  if (url.startsWith('@cloud://') || url.startsWith('cloud://')) {
    try {
      return await getTempFileURL(url);
    } catch (error) {
      console.error('获取临时URL失败:', error);
      // 如果有映射，作为备用方案
      if (imageUrlMap[url]) {
        return imageUrlMap[url];
      }
      return '';
    }
  }
  
  // 其他情况直接返回原URL
  return url;
};

// 转换云存储文件URL为临时URL（通用函数）
const getTempFileURL = (url) => {
  return new Promise((resolve, reject) => {
    if (!url || typeof url !== 'string') {
      reject(new Error('Invalid URL'));
      return;
    }

    // 如果不是云存储URL，直接返回
    if (!url.startsWith('cloud://') && !url.startsWith('@cloud://')) {
      resolve(url);
      return;
    }

    // 去掉可能的@前缀
    const cleanUrl = url.startsWith('@') ? url.substring(1) : url;

    // 获取云存储文件的临时链接
    wx.cloud.getTempFileURL({
      fileList: [cleanUrl],
      success: (res) => {
        if (res.fileList && res.fileList.length > 0 && res.fileList[0].tempFileURL) {
          resolve(res.fileList[0].tempFileURL);
        } else {
          reject(new Error('Failed to get temp file URL'));
        }
      },
      fail: (error) => {
        console.error('获取临时链接失败:', error);
        reject(error);
      }
    });
  });
};

// 转换云存储视频URL为临时URL（保持向后兼容）
const convertCloudVideoUrl = getTempFileURL;

// 转换云存储图片URL为临时URL
const convertCloudImageUrl = getTempFileURL;

module.exports = {
  formatTime,
  getLocalUrl,
  convertCloudUrl,
  convertCloudUrlAsync,
  convertCloudVideoUrl,
  convertCloudImageUrl,
  getTempFileURL,
};
